package larrys.pomodoro.security;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import larrys.pomodoro.Constant;
import larrys.pomodoro.domain.exception.PomodoroException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.MessageSource;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

@Component
public class AuthFailureHandler implements AuthenticationFailureHandler {

	private String defaultAuthFailureMessage = "Incorrect Email or Password";
	private String loginPageUrl = "/pages/loginpage";
	private MessageSource messageSource;

	@Required
	@Autowired
	public void setMessageSource(MessageSource messageSource) {
		this.messageSource = messageSource;
	}

	@Override
	public void onAuthenticationFailure(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException exception)
			throws IOException, ServletException {

		String errorMessage = defaultAuthFailureMessage;
		Locale locale = (Locale) request.getSession().getAttribute(
				SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME);
		if (exception.getCause() instanceof PomodoroException) {
			String exceptionCode = ((PomodoroException) exception.getCause())
					.getExceptionCode();
			errorMessage = messageSource.getMessage(
					Constant.EXCEPTION_MSG_CODE_PRIFIX + exceptionCode, null,
					defaultAuthFailureMessage, locale);
		}
		String encodedMessage = "?loginerror="
				+ URLEncoder.encode(errorMessage, "UTF-8");
		response.sendRedirect(request.getContextPath() + loginPageUrl
				+ encodedMessage);
	}
}
